﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class Pages_ShoppingCart : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // populate the control only on the initial page load
        if (!IsPostBack)
            PopulateControls();
    }
    // fill shopping cart controls with data
    private void PopulateControls()
    {
        // set the title of the page
        this.Title = PresentsConfiguration.SiteName + " : Shopping Cart";
        // get the items in the shopping cart
        DataTable dt = ShoppingCartAccess.GetItems();
        // if the shopping cart is empty...
        if (dt.Rows.Count == 0)
        {
            titleLabel.Text = "Ваша корзина пуста!";
            grid.Visible = false;
            updateButton.Enabled = false;
            checkoutButton.Enabled = false;
            totalAmountLabel.Text = String.Format("{0:c}", 0);
        }
        else
        // if the shopping cart is not empty...
        {
            // populate the list with the shopping cart contents
            grid.DataSource = dt;
            grid.DataBind();
            // setup controls
            titleLabel.Text = "Здесь представлены товары, которые Вы добавили в корзину:";
            grid.Visible = true;
            updateButton.Enabled = true;
            checkoutButton.Enabled = true;
            // display the total amount
            decimal amount = ShoppingCartAccess.GetTotalAmount();
            totalAmountLabel.Text = String.Format("{0:c}", amount);
        }
    }
    protected void grid_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        // Index of the row being deleted
        int rowIndex = e.RowIndex;
        // The ID of the product being deleted
        string productId = grid.DataKeys[rowIndex].Value.ToString();
        // Remove the product from the shopping cart
        bool success = ShoppingCartAccess.RemoveItem(productId);
        // Display status
        statusLabel.Text = success ? "<br />Товар успешно удалён из корзины!<br />" :
        "<br />Произошла ошибка при удалении товара из корзины!<br />";
        // Repopulate the control
        PopulateControls();
    }
    protected void updateButton_Click(object sender, EventArgs e)
    {
        // Number of rows in the GridView
        int rowsCount = grid.Rows.Count;
        // Will store a row of the GridView
        GridViewRow gridRow;
        // Will reference a quantity TextBox in the GridView
        TextBox quantityTextBox;
        // Variables to store product ID and quantity
        string productId;
        int quantity;
        // Was the update successful?
        bool success = true;
        // Go through the rows of the GridView
        for (int i = 0; i < rowsCount; i++)
        {
            // Get a row
            gridRow = grid.Rows[i];
            // The ID of the product being deleted
            productId = grid.DataKeys[i].Value.ToString();
            // Get the quantity TextBox in the Row
            quantityTextBox = (TextBox)gridRow.FindControl("editQuantity");
            // Get the quantity, guarding against bogus values
            if (Int32.TryParse(quantityTextBox.Text, out quantity))
            {
                // Update product quantity
                success = success && ShoppingCartAccess.UpdateItem(productId, quantity);
            }
            else
            {
                // if TryParse didn't succeed
                success = false;
            }
            // Display status message
            statusLabel.Text = success ?
            "<br />Ваша корзина успешно обновлена!<br />" :
            "<br />Обновлено с ошибкой! Пожалуйста проверте Вашу корзину!<br />";
        }
        // Repopulate the control
        PopulateControls();
    }
    protected void continueShoppingButton_Click(object sender, EventArgs e)
    {
        // redirect to the last visited catalog page, or to the
        // main page of the catalog
        object page;
        if ((page = Session["LastVisitedCatalogPage"]) != null)
            Response.Redirect(page.ToString());
        else
            Response.Redirect(Request.ApplicationPath + "Default.aspx");
    }
    protected void checkoutButton_Click(object sender, EventArgs e)
    {
        string redirect = "Checkout.aspx";
        Response.Redirect("Checkout.aspx");
        // Store the total amount because the cart
        // is emptied when creating the order
        decimal amount = ShoppingCartAccess.GetTotalAmount();
        // Create the order and store the order ID
        string orderId = ShoppingCartAccess.CreateOrder();
        // Obtain the site name from the configuration settings
        string siteName = PresentsConfiguration.SiteName;
        // Create the PayPal redirect location
        redirect = "";
        redirect += "https://www.paypal.com/xclick/business=youremail@server.com";
        redirect += "&item_name=" + siteName + " Order " + orderId;
        redirect += "&item_number=" + orderId;
        redirect += "&amount=" + String.Format("{0:0.00} ", amount);
        redirect += "&currency=USD";
        redirect += "&return=http://www." + siteName + ".com";
        redirect += "&cancel_return=http://www." + siteName + ".com";
        // Redirect to the payment page
        Response.Redirect(redirect);
    }
}